package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022-12-01 13:29
 */
@RestController
@RequestMapping("/api/user/passport")
@SuppressWarnings("all")
public class PassportApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     * /api/user/passport/login
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        // 获取用户信息 -- 验证是否存在用户
        UserInfo user = userService.login(userInfo);
        if(user != null) {
            // 不等于空说明已经匹配上返回了用户信息
            // 使用UUID生成token
            String token = UUID.randomUUID().toString().replace("-", "");
            // 做安全性限制，token中要对应ip和用户id
            String ip = IpUtil.getIpAddress(request);
            JSONObject object = new JSONObject();
            object.put("ip", ip);
            object.put("userId", user.getId());

            // 存储到redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,
                    object.toJSONString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);


            // 返回页面信息
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("nickName", user.getNickName());
            resultMap.put("token", token);
            return Result.ok(resultMap);
        }else {
            return Result.fail().message("用户名或者密码错误！！！");
        }

    }

    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        // 从Redis中删除对应的token
        // 获取token，需要请求对象
        String token = request.getHeader("token");
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
        return Result.ok();
    }
}
